
const router = require('koa-router')();
const mysqlApi = require('../lib/mysql');
const moment = require('moment')


//主页
router.get('/aa', async (ctx, next) => {
	console.log(222)
 // ctx.redirect('essay')
let res
res=[]
res[0]=1
res[1]=2
await ctx.render('essay.ejs', {
    session:222,
    essay: res
  })

})

//文章页面
router.get('/essay', async (ctx, next) => {
  let res

  await mysqlApi.seletEssay_tableAll().then(win => {
    res = win
  })
  await ctx.render('essay.ejs', {
    session: ctx.session,
    essay: res
  })
})

//单篇文章
router.get('/essay/:essayId', async (ctx, next) => {
  let essayId = ctx.params.essayId;
  let res
  let comments = []
  //文章
  await mysqlApi.seletEssay_tableId(essayId).then(win => {
    res = win
  })
  //评论
  await mysqlApi.seletComment_tableEssayId(essayId).then(win => {
    comments = win
  })
  await ctx.render('essayIts.ejs', {
    session: ctx.session,
    Edata: res,
    comments: comments
  })
})

//编辑页面
router.get('/essay/edit/:essayId', async (ctx, next) => {
  let essayId = ctx.params.essayId
  let editData
  await mysqlApi.seletEssay_tableId(essayId).then(win => {
    editData = win[0]
  })
  await ctx.render('essayEdit.ejs', {
    session: ctx.session,
    data: editData
  })
})

//编辑提交
router.post('/essay/edit', async (ctx, next) => {
  let data = ctx.request.body
  let time = moment().format('YYYY-MM-DD HH:mm')
  if (data.title && data.content && data.ID) {
    await mysqlApi.updateEssay_tableId([data.title, data.content, time, data.ID]).then(win => {
      ctx.body = {
        code: 200,
        msg: '编辑成功'
      }
    })
  } else {
    ctx.body = {
      code: 400,
      msg: '不能为空'
    }
  }
})

//删除
router.post('/essay/del', async (ctx, next) => {
  let data = ctx.request.body
  await mysqlApi.delEssay_table(data.ID).then(win => {
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  })

})


module.exports = router
